package com.vecharm.app.ui.web

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.webkit.CookieManager
import android.webkit.WebResourceResponse
import android.webkit.WebView
import com.ling.sdk.utils.Cache
import com.tencent.sonic.sdk.SonicRuntime
import com.tencent.sonic.sdk.SonicSessionClient
import java.io.InputStream
import java.util.*

class SonicRuntimeImpl(context: Context) : SonicRuntime(context) {
    companion object {
        var userAgent1 = Cache.get("userAgent", "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Mobile Safari/537.36")

        fun cacheUserAgent(userAgent: String) {
            Cache.put("userAgent", userAgent)
        }

    }

    /**
     * 获取用户UA信息
     * @return
     */

    override fun getUserAgent() = userAgent1


    /**
     * 获取用户ID信息
     * @return
     */

    override fun getCurrentUserAccount() = "sonic-app"

    override fun isNetworkValid() = true

    override fun getCookie(url: String): String? {
        val cookieManager = CookieManager.getInstance()
        return cookieManager.getCookie(url)
    }

    override fun log(tag: String, level: Int, message: String) {
        when (level) {
            Log.ERROR -> Log.e(tag, message)
            Log.INFO -> Log.i(tag, message)
            else -> Log.d(tag, message)
        }
    }

    override fun createWebResourceResponse(mimeType: String, encoding: String, data: InputStream, headers: Map<String, String>): Any {
        val resourceResponse = WebResourceResponse(mimeType, encoding, data)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            resourceResponse.responseHeaders = headers
        }
        return resourceResponse
    }

    override fun showToast(text: CharSequence, duration: Int) {

    }

    override fun notifyError(client: SonicSessionClient?, url: String?, errorCode: Int) {

    }

    override fun isSonicUrl(url: String) = true

    override fun setCookie(url: String, cookies: List<String>?): Boolean {
        if (!TextUtils.isEmpty(url) && cookies != null && cookies.isNotEmpty()) {
            val cookieManager = CookieManager.getInstance()
            for (cookie in cookies) {
                cookieManager.setCookie(url, cookie)
            }
            return true
        }
        return false
    }

    override fun postTaskToThread(task: Runnable, delayMillis: Long) {
        val thread = Thread(task, "SonicThread")
        thread.start()
    }

    override fun getHostDirectAddress(url: String) = null

    /*   override fun getSonicCacheDir(): File {

           return if (isSupportedSD()) {
               try {
                   val path = Environment.getExternalStorageDirectory().absolutePath + File.separator + "sonic/"
                   val file = File(path.trim { it <= ' ' })
                   if (!file.exists()) {
                       file.mkdir()
                   }
                   return file
               } catch (e: Exception) {
                   super.getSonicCacheDir()
               }
           } else {
               super.getSonicCacheDir()
           }
       }*/

}


private fun isSupportedSD() = Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() || !Environment.isExternalStorageRemovable()

class SonicSessionClientImpl : SonicSessionClient() {

    var webView: WebView? = null
        private set

    fun bindWebView(webView: WebView) {
        this.webView = webView
    }

    override fun loadUrl(url: String?, extraData: Bundle?) {
        url ?: return
        webView?.loadUrl(url)
    }

    override fun loadDataWithBaseUrl(baseUrl: String, data: String, mimeType: String, encoding: String, historyUrl: String) {
        webView?.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl)
    }


    override fun loadDataWithBaseUrlAndHeader(baseUrl: String, data: String, mimeType: String, encoding: String, historyUrl: String, headers: HashMap<String, String>) {
        loadDataWithBaseUrl(baseUrl, data, mimeType, encoding, historyUrl)
    }

}

